package com.hdax.realm;

import com.hdax.entity.Permission;
import com.hdax.service.UserService;
import com.hdax.vo.ActiveUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.DispatcherServlet;

import java.util.List;


public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService service;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        ActiveUser user = (ActiveUser) principal.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<Permission> permissions = service.findById(user.getId()).getRole().getPermissions();
        for (Permission permission : permissions) {
            info.addStringPermission(permission.getName());
        }
        System.out.println(info.getStringPermissions()+"!!!!!!!!!!!!!!!!!!!");
        System.out.println(info.getStringPermissions().size());
//        System.out.println(info+"!!!!!!!!!!!!!!!!!!!!!!!!");
        return info;

    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        ActiveUser user = service.selectUserByName(username);
        if (user == null) {
            return null;
        }
        if (user.getDisable().equals("true")) {
            throw new DisabledAccountException("该用户被禁用");
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
    }
}
